package com.nip.commons.xmlconfig.xml;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomHelper {

	/**
	 * @param tag_name
	 * @param nodeList
	 * @return
	 */
	private Node getNode(String tag_name, NodeList nodeList)
	{
		if(tag_name == null)
		{
			throw new NullPointerException("Tag name is null");
		}
		
		if(nodeList == null)
		{
			throw new NullPointerException("NodeList is null");
		}
		
		for(int i = 0 ; i< nodeList.getLength() ; i++)
		{
			Node node = nodeList.item(i);
			if(node.getNodeName().equalsIgnoreCase(tag_name))
				return node;
		}
		
		throw new NullPointerException(String.format("Node %s not found.", tag_name));
	}
	
	/**
	 * @param strTag
	 * @param nodeList
	 * @return
	 */
	public Node getNodeSequenTag(String strTag, NodeList nodeList)
	{
		String[] strtag = strTag.split("\\.");
		Node node = null;
		NodeList nodes = nodeList;
		for(String tag_name : strtag)
		{
			node = getNode(tag_name,nodes);
			nodes = node.getChildNodes();
		}
		
		return node;
		
	}
	
	/**
	 * @param strTag
	 * @param nodeList
	 * @return
	 */
	public NodeList getNodesSequenTag(String strTag, NodeList nodeList)
	{
		String[] strtag = strTag.split("\\.");
		Node node = null;
		NodeList nodes = nodeList;
		for(String tag_name : strtag)
		{
			node = getNode(tag_name,nodes);
			nodes = node.getChildNodes();
		}
		
		return nodes;
		
	}
	
	public String getNodeValue(Node node)
	{
		if(node == null)
		{
			throw new NullPointerException("Node is null");
		}
		
		return node.getTextContent();
	}
	
	public String getAttValue(String attname, Node node)
	{
		if(node == null)
		{
			throw new NullPointerException("Node is null");
		}
		
		NamedNodeMap atts = node.getAttributes();
		
		for(int i = 0 ; i < atts.getLength() ; i++)
		{
			if(atts.item(i).getNodeName().equalsIgnoreCase(attname))
				return atts.item(i).getNodeValue();
		}
		throw new NullPointerException(String.format("Attribute %s not found.", attname));
		
	}
}
